<?php
namespace control;
// 资产折旧明细
class assetDepreciationMxClass extends adIndexClass
{
    private const page = 'assetDepreciationMx';         # 权限
    private const table = 'asset_depreciation';        # 数据表
    private const tableMx = 'asset_depreciation_detail'; # 子表
    private const title = '资产折旧明细';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'month'          => [
                        'name'  => "会计期间",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'acid'          => [
                        'name'  => "分类",
                        'width' => 150,
                    ],
                    'orderNo'          => [
                        'name'  => "固定资产编码",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '名称',
                        'width' => 150,
                    ],
                    'brand'         => [
                        'name'  => '品牌',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '计量单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'discountYear'          => [
                        'name'  => '折旧年限(月)',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'purchaseMoney'          => [
                        'name'  => '资产原值',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'depreciationMoney'          => [
                        'name'  => '期初累计折旧',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '预计净残值',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'monthDecMoney'          => [
                        'name'  => '本月折旧',
                        'width' => 100,
                    ],
                    'ratio'          => [
                        'name'  => '月折旧率',
                        'width' => 100,
                    ],
                    'discountMoney'          => [
                        'name'  => '期末累计折旧',
                        'width' => 100,
                    ],
                    'residue'          => [
                        'name'  => '期末剩余计提',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(
                        [
                            'name' => 'date',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                    "固定资产编码" => text(array("name" => "orderNo")),
                    "名称" => text(array("name" => "name")),
                ],
                [
                    "分类" => selectMultiple(["name" => "acid", 'table' => "asset_catalog",'where'=>"coid = '".self::$coid."' order by list asc,time asc", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                    "开始使用日期" => text(
                        [
                            'name' => 'recordDate',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*固定资产入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData' class='spanButton'>导出</a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*固定资产列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'a.coid' => self::$coid,
            'c.acid' =>$this->post('acid')
        ];
        $like = [
            'c.orderNo' => $this->post('orderNo'),
        ];
        //生成查询语句

        $where .= search([
            "=" => $equal,
            "like" => $like,
        ]);
        if ($this->post('date')) {
            $arr = explode(' ~ ', $this->post('date'));
            $where .= " and a.month >='".$arr[0]."' and a.month <= '".$arr[1]."'";
        }
        if ($this->post('recordDate')) {
            $where .= self::timeComparison($this->post('recordDate'), 'date', 'a.recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.recordDate desc,a.orderNo desc,b.list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        $page = $this->page([
            'field'=>"c.*,a.month",
            "table" => self::table.' as a join '.self::tableMx.' as b on a.id = b.orderId join asset as c on b.atid = c.id',
            "where" => $where,
            "order" => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $endDate = $array['month'].'-'.sprintf('%02d',date('t',strtotime($array['month'])));
            $ratio = assetManagementClass::monthRatio($array['depreciationMethod'],$array['discountYear'],$array['money'],$array['purchaseMoney'],$array['depreciationMoney'],$array['purchaseDate'],$endDate,1);
            $monthDecMoney =assetManagementClass::monthDecMoney($array['depreciationMethod'],$array['purchaseMoney'],$ratio/100,$array['purchaseDate'],$endDate,$array['discountYear'],$array['money'],$array['depreciationMoney']);
            $discountMoney = assetManagementClass::calcSalvage($array['depreciationMethod'],$monthDecMoney,$array['purchaseDate'],$array['discountYear'],$array['purchaseMoney'],$array['money'],$array['depreciationMoney'],$endDate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'acid':
                        $row[] = assetCatalogClass::getCatalogName($array['acid']);
                        break;
                    case 'monthDecMoney':
                        $row[] = $monthDecMoney;
                        break;
                    case 'ratio':
                        $row[] = $ratio.'%';
                        break;
                    case 'discountMoney':
                        $row[] = $discountMoney;
                        break;
                    case 'residue':
                        $row[] = round($array['purchaseMoney']-$discountMoney-$array['money'],2);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }



    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        $append = [];
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'isDelete';
                $form = self::page . 'OperateForm, listForm';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'append' => $append,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {

        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = ['会计期间', '分类', '固定资产编码', '名称', '品牌', '规格型号', '计量单位', '数量', '折旧年限(月)', '资产原值', '期初累计折旧', '预计净残值', '本月折旧', '月折旧率', '期末累计折旧', '期末剩余计提'];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $endDate = $array['month'].'-'.sprintf('%02d',date('t',strtotime($array['month'])));
                    $ratio = assetManagementClass::monthRatio($array['depreciationMethod'],$array['discountYear'],$array['money'],$array['purchaseMoney'],$array['depreciationMoney'],$array['purchaseDate'],$endDate,1);
                    $monthDecMoney =assetManagementClass::monthDecMoney($array['depreciationMethod'],$array['purchaseMoney'],$ratio/100,$array['purchaseDate'],$endDate,$array['discountYear'],$array['money'],$array['depreciationMoney']);
                    $discountMoney = assetManagementClass::calcSalvage($array['depreciationMethod'],$monthDecMoney,$array['purchaseDate'],$array['discountYear'],$array['purchaseMoney'],$array['money'],$array['depreciationMoney'],$endDate);
                    //本列
                    $tr[] = [
                        $array['month'], assetCatalogClass::getCatalogName($array['acid']), $array['orderNo'], $array['name'], $array['brand'],$array['model'],$array['unit'],
                        $array['num'],$array['discountYear'],$array['purchaseMoney'],$array['depreciationMoney'],$array['money'],$monthDecMoney,$ratio.'%',$discountMoney, round($array['purchaseMoney']-$discountMoney,2)
                    ];
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
